package com.slliver.sentinelservice.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.slliver.commonmodel.pay.Pay;
import com.slliver.commonmodel.product.Product;
import com.slliver.sentinelservice.openfeign.ProductFeignClient;
import com.slliver.sentinelservice.service.SentinelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;


@Service
public class SentinelServiceImpl implements SentinelService {

    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "sentinel-createPay", blockHandler = "savePayFallback")
    //@SentinelResource(value = "sentinel-createPay")
    @Override
    public Pay savePay(Long userId, Long productId) {
        Product product = productFeignClient.getProductById(productId, "accessToken="+ LocalDateTime.now());
        Pay pay = new Pay();
        pay.setId(1001L);
        pay.setCreateDateTime(LocalDateTime.now());
        pay.setUserId(userId);
        pay.setProductList(Arrays.asList(product));
        if(product.getNum() > 0){
            pay.setRemark("正常流程：商品下单成功了");
        }else{
            pay.setRemark("异常流程：商品下单失败了");
        }
        return pay;
    }

    // 执行兜底回调
    public Pay savePayFallback(Long userId, Long productId, BlockException e){
        Pay pay = new Pay();
        pay.setId(0L);
        pay.setCreateDateTime(LocalDateTime.now());
        pay.setUserId(userId);
        pay.setRemark("错误流程：sentinel流量进行保护");
        return pay;
    }
}
